package com.aabte.nettyleran.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedFile;
import io.netty.handler.stream.ChunkedWriteHandler;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaderUtil.isKeepAlive;
import static io.netty.handler.codec.http.HttpHeaderUtil.setContentLength;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * 使用Netty实现一个简单的Http文件服务器
 *
 * @author Daniel
 * @version 1.0
 * @date 2020/3/14
 */
public class HttpFileServer {

    public static final String DEFAULT_URL = System.getProperty("user.dir");

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        String url = DEFAULT_URL;
        if (args != null && args.length > 1) {
            url = args[1];
        }

        new HttpFileServer().run(port, url);

    }

    private void run(final int port, final String url) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));
                        socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                        socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        socketChannel.pipeline().addLast("file-server-handler", new HttpFileServerHandler(url));
                    }
                });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

        private String url;

        public HttpFileServerHandler(String url) {
            this.url = url;
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
            if (!request.decoderResult().isSuccess()) {
                sendError(ctx, BAD_REQUEST);
                return;
            }

            final String uri = request.uri();
            final String path = sanitizeUri(uri);
            if (null == path) {
                sendError(ctx, FORBIDDEN);
                return;
            }

            File file = new File(path);
            if (file.isHidden() || !file.exists()) {
                sendError(ctx, NOT_FOUND);
                return;
            }

            if (file.isDirectory()) {
                if (uri.endsWith("/")) {
                    sendListing(ctx, file);
                } else {
                    sendRedirect(ctx, uri + "/");
                }
                return;
            }

            if (!file.isFile()) {
                sendError(ctx, FORBIDDEN);
                return;
            }

            RandomAccessFile randomAccessFile;
            try {
                randomAccessFile = new RandomAccessFile(file, "r");
            } catch (FileNotFoundException e) {
                sendError(ctx, NOT_FOUND);
                return;
            }

            long fileLength = randomAccessFile.length();
            DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            setContentLength(response, fileLength);
            setContentTypeHeader(response, file);
            if (isKeepAlive(request)) {
                response.headers().set(CONNECTION, KEEP_ALIVE);
            }
            ctx.write(response);
            ChannelFuture channelFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise());
            channelFuture.addListener(new ChannelProgressiveFutureListener() {
                @Override
                public void operationProgressed(ChannelProgressiveFuture channelProgressiveFuture, long progress, long total) throws Exception {
                    if (total < 0) {
                        System.err.println("Transfer progress: " + progress);
                    } else {
                        System.err.println("Transfer progress: " + progress + "/" + total);
                    }
                }

                @Override
                public void operationComplete(ChannelProgressiveFuture channelProgressiveFuture) throws Exception {
                    System.out.println("Transfer complete.");
                }
            });
            ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            if (!isKeepAlive(request)) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }

        }

        private void sendRedirect(ChannelHandlerContext ctx, String uri) {
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
            response.headers().set(LOCATION, uri);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }

        private void setContentTypeHeader(DefaultHttpResponse response, File file) {
            MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
            response.headers().set(CONTENT_TYPE, mimetypesFileTypeMap.getContentType(file.getPath()));
        }

        private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9.]*");

        private void sendListing(ChannelHandlerContext ctx, File dir) {
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
            response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
            StringBuilder sbuf = new StringBuilder();
            String dirPath = dir.getPath();
            sbuf.append("<!DOCTYPE html>\r\n");
            sbuf.append("<html><head><title>");
            sbuf.append(dirPath);
            sbuf.append(" 目录: ");
            sbuf.append("</title></head><body>\r\n");
            sbuf.append("<h3>");
            sbuf.append(dirPath).append(" 目录: ");
            sbuf.append("</h3>\r\n");
            sbuf.append("<ul>");
            sbuf.append("<li>链接: <a href=\"../\">..</a></li>\r\n");

            File[] files = dir.listFiles();
            if (null != files) {
                for (File f : files) {
                    if (f.isHidden() || !f.canRead()) {
                        continue;
                    }

                    String name = f.getName();
                    if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
                        continue;
                    }

                    sbuf.append("<li>链接: <a href=\"");
                    sbuf.append(name);
                    sbuf.append("\">");
                    sbuf.append(name);
                    sbuf.append("</a></li>\r\n");
                }
            }
            sbuf.append("</ul></body></html>\r\n");
            ByteBuf byteBuf = Unpooled.copiedBuffer(sbuf, StandardCharsets.UTF_8);
            response.content().writeBytes(byteBuf);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }

        public static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");

        private String sanitizeUri(String uri) {
            try {
                uri = URLDecoder.decode(uri, StandardCharsets.UTF_8.toString());
            } catch (UnsupportedEncodingException e) {
                try {
                    uri = URLDecoder.decode(uri, StandardCharsets.ISO_8859_1.toString());
                } catch (UnsupportedEncodingException ex) {
                    throw new IllegalArgumentException(ex);
                }
            }

            if (!uri.startsWith("/")) {
                return null;
            }

            uri = uri.replace('/', File.separatorChar);
            if (uri.contains(File.separator + '.')
                    || uri.contains('.' + File.separator)
                    || uri.startsWith(".")
                    || uri.endsWith(".")
                    || INSECURE_URI.matcher(uri).matches()) {
                return null;
            }

            return this.url + File.separator + uri;
        }

        private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
            ByteBuf byteBuf = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", StandardCharsets.UTF_8);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, byteBuf);
            response.headers().set(CONTENT_TYPE, "text/plain;charset=UTF-8");
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
